package netty.demo_05_GroupChat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * Netty应用实例-群聊系统
 * 客户端
 *
 * @author chenyuan
 * @date 2020/11/10 15:06
 */
public class ChatClient {
	// 主机地址
	private final String HOST;
	// 端口号
	private final int PORT;

	public ChatClient(String HOST, int PORT) {
		this.HOST = HOST;
		this.PORT = PORT;
	}

	public void run() throws InterruptedException {
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(eventLoopGroup)
					.channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline pipeline = socketChannel.pipeline();
							pipeline.addLast("decoder", new StringDecoder());
							pipeline.addLast("encoder", new StringEncoder());
							pipeline.addLast(new ChatClientHandler());
						}
					});

			System.out.println("客户端准备完毕");
			ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();

			Channel channel = channelFuture.channel();
			System.out.println("------ " + channel.localAddress() + " ------");
			// 因为客户端需要输入信息，所以需要扫描器
			Scanner scanner = new Scanner(System.in);
			while (scanner.hasNextLine()) {
				String s = scanner.nextLine();
				// 通过 Channel 发送到 服务端
				channel.writeAndFlush(s + "\r\n");
			}

			channelFuture.channel().closeFuture().sync();
		} finally {
			eventLoopGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		new ChatClient("localhost", 8000).run();
	}
}
